package per.jdz.demo.readlistener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author Jdz
 * @date 2025/2/5
 */
@Slf4j
public class GenericReadListener<T> implements ReadListener<T> {
    private final int BATCH_SIZE = 1000;
    private final List<T> currentBatch;
    private final Consumer<T> preProcessCallback;
    private final BatchProcessor<T> batchProcessor;
    private final String fileName;
    public GenericReadListener(String fileName, Consumer<T> preProcessCallback, BatchProcessor<T> batchProcessor) {
        this.currentBatch = new ArrayList<>(BATCH_SIZE);
        this.preProcessCallback = preProcessCallback;
        this.batchProcessor = batchProcessor;
        this.fileName = fileName;
    }
    @Override
    public void invoke(T data, AnalysisContext analysisContext) {
        if (preProcessCallback != null) {
            preProcessCallback.accept(data);
        }
//        log.info(data.toString());
        // 将数据添加到当前批次
        currentBatch.add(data);
        if (currentBatch.size() == BATCH_SIZE) {
            // 写入当前批次的数据到新文件
            batchProcessor.processBatch(currentBatch);
            // 清空当前批次
            currentBatch.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 如果还有剩余未写入的数据，则写入最后一批
        if (!currentBatch.isEmpty()) {
            batchProcessor.processBatch(currentBatch);
        }
        log.info("{}: 所有数据已处理完毕", fileName);
    }
    @FunctionalInterface
    public interface BatchProcessor<T> {
        void processBatch(List<T> batch);
    }
}
